<template>
  <div class="referEmp">
    <h3>教职员查询</h3>
    <div class="table">
      <div style="padding: 20px;">
        <el-row :gutter="20" type="flex" justify="space-between">
          <el-col :span="6">
            <el-button-group class="flex">
              <el-select v-model="empPluralityTypeId" size="medium" multiple collapse-tags filterable clearable placeholder="选择工作类型">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_emp_type" :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small" @click="empPluralityTypeId = Object.keys(dict_emp_type)">全选</el-button>
            </el-button-group>
          </el-col>
          <el-col :span="5">
            <el-button-group class="flex">
              <el-select v-model="age" size="medium" multiple filterable collapse-tags clearable placeholder="选择年龄">
                <el-option :label="item+'岁'" :value="item" v-for="(item,index) in ageArr" :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small" @click="selectAgeAll">全选</el-button>
            </el-button-group>
          </el-col>
          <el-col :span="6">
            <el-date-picker
            style="width: 80%;"
            size="medium"
              v-model="selectDate"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="-"
              start-placeholder="选择开始日期"
              end-placeholder="选择结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-col>
          <el-col :span="4">
            <el-select v-model="professionTypeId" size="medium" collapse-tags filterable clearable placeholder="选择职位/职务 ">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_profession_type" :key="index"></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="empstatusId" style="float: right;width: 100%" size="medium" collapse-tags filterable clearable placeholder="选择在职状态">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_employee_status" :key="index"></el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row :gutter="20" type="flex" justify="space-between" style="margin-top: 20px;">
          <el-col :span="6" style="display: flex;">
            <el-button type="success" size="medium" icon="el-icon-download" @click="exportAllDataEvent">导出</el-button>
            <el-button type="success" size="medium" icon="el-icon-printer" @click="printEvent">打印</el-button>
            <el-button type="success" size="medium" icon="el-icon-plus" @click="empInsert" v-if="roleId%14!=3">新增</el-button>
          </el-col>
          <el-col :span="6">
            <el-select v-model="sportId" :disabled="SportDisabled" @change="sportChange" size="medium" collapse-tags filterable clearable placeholder="选择运动项目">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="sportItemId" :disabled="sportId==''" size="medium" collapse-tags filterable clearable placeholder="选择运动小项">
              <el-option :label="item.name" :value="item.sportItemId" v-for="(item,index) in sportItemData" :key="index"></el-option>
            </el-select>
          </el-col>
          <el-col :span="4" style="display: flex;">
            <el-button type="success" size="medium" icon="el-icon-s-promotion" @click="searchSubmit" style="margin-right: 10px;">搜索</el-button>
            <el-button @click="clearTableFilter" size="medium" type="warning" icon="el-icon-refresh-right"> 清空</el-button>
          </el-col>
          <el-col :span="4">
            <vxe-input style="float: right;width: 100%" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @input="searchEvent"></vxe-input>
          </el-col>
        </el-row>
      </div>
      <vxe-table resizable show-overflow border ref="empTable" max-height="700" keep-source border stripe highlight-hover-row highlight-current-row  @sort-change="sortChange" :loading="loading" :data="empData">
        <vxe-table-column field="name" title="姓名" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="idNo" width="160" title="身份证" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="genderName" title="性别" sortable :filters="[{label: '男', value: '男'}, {label: '女', value: '女'}]"></vxe-table-column>
        <vxe-table-column field="age" title="年龄" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="empType" title="专职" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="heightName" title="兼职" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="workDate" title="入职时间" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="teachDate" title="执教时间" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="leaveDate" title="离职时间" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="professionType" title="职位/职务" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="empStatus" title="在职状态" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="sport" title="运动项目" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="sportItem" title="运动小项" sortable :filters="[{ data: '' }]" :filter-method="customStringFilterMethod">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="" title="操作" width="100">
          <template #default="{ row }">
            <div class="">
              <el-tooltip class="item" effect="dark" content="档案管理" placement="top">
                <el-button @click="empDetail(row)" size="medium"  type="success" icon="el-icon-setting" circle></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="档案打印" placement="top">
                <el-button @click="detailPrintModelShow(row)" size="medium" type="info" icon="el-icon-printer" circle></el-button>
              </el-tooltip>
            </div>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize"
        :total="page.totalResult" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
        @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <vxe-modal v-model="printModal" title="定制您的打印" width="600px">
      <template #default>
        <div class="print print-top">
          <el-button @click="topClick(item,index)" type="success" v-for="item,index in printTopData" :key="index">{{dict_print[item]}}</el-button>
        </div>
        <div class="print print-bottom">
          <el-button @click="bottomClick(item,index)" type="infor" v-for="item,index in printbottomData" :key="index">{{dict_print[item]}}</el-button>
        </div>
        <div style="display: flex;justify-content: center;margin-top: 10px;">
          <el-button @click="refreshPrint" type="success" icon="el-icon-refresh">重置</el-button>
          <el-button @click="selectPrint" type="success" icon="el-icon-check">全选</el-button>
          <el-button @click="empDetailPrint" type="success" v-loading.fullscreen.lock="fullscreenLoading" icon="el-icon-printer">打印</el-button>
          <el-button @click="clearPrint" type="warning">取消</el-button>
        </div>
      </template>
    </vxe-modal>
    <div style="visibility: hidden;overflow: hidden;height: 10px;">
      <empDetailPrint ref="empDetailPrint" :detailData="detailData" />
    </div>
  </div>
</template>

<script>
  import { getPersonByOrgEmp,empInit,sport_item_by_sportId,getAllEmp,getDetail } from '@/api/person.js'
  import { employee_type,profession_type,employee_status,sport_by_org,sport_item } from '@/api/dict.js'
  import empDetailPrint from '@/components/print/empDetailPrint.vue'
  export default {
    components: {empDetailPrint},
    data() {
      return {
        roleId: window.localStorage.getItem('roleId'),
        fullscreenLoading: false,
        pId: '',
        printTopData: [],
        printbottomData: ['emp_basic','emp_detail','family','emp_languageLevel','emp_workExp','education','emp_paper','emp_referee','emp_rewordPunishment','emp_furtherEdu'],
        dict_print: {
          'emp_basic': '基本信息',
          'emp_detail': '详细信息',
          'family': '家庭成员',
          'education': '教育经历',
          'emp_referee': '裁判等级',
          'emp_workExp': '任职经历',
          'emp_furtherEdu': '进修培训',
          'emp_paper': '学术论文',
          'emp_languageLevel': '外语水平',
          'emp_rewordPunishment': '奖惩情况',
        },
        printModal: false,
        empData: [],
        defaultEmpData: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        dict_emp_type: {},
        dict_profession_type: {},
        dict_employee_status: {},
        dict_sport: {},
        dict_sport_item: {},
        dict_idNo: {},
        filterName: '',
        empPluralityTypeId: '',
        age: '',
        sportId: '',
        sportItemId: '',
        sportItemData: [],
        professionTypeId: '',
        empstatusId: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        selectDate: '',
        detailData: {},
        searchProps: [],
        ageArr: [],
        search: false,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.getEmp()
      })
    },
    watch: {
      filterName(val) {
        if(!val){
          this.page = {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0,
          }
          this.search = false
          this.findList()
        }
      }
    },
    computed: {
      SportDisabled() {
        if(this.empPluralityTypeId && this.empPluralityTypeId.indexOf("1") > -1) {
          return false
        }else{
          return true
        }
      }
    },
    methods: {
      openFullScreen1() {
        setTimeout(() => {
        }, 2000);
      },
      detailPrintModelShow(row) {
        this.pId = row.pid
        this.refreshPrint()
        this.printModal = true
      },
      empDetailPrint() {
        if(this.printTopData.length != 0){
          this.fullscreenLoading = true;
          let data = {
            pId: this.pId,
            data: {personInfoPrintSpec: this.printTopData.join(',')}
          }
          this.detailData = {}
          getDetail(data).then(res=>{
            if(res.code === 200) {
              this.detailData = res.data
              setTimeout(()=>{
                this.$refs.empDetailPrint.tablePrint()
                this.fullscreenLoading = false;
              },200)
            }else{
              this.$message.warning('没有可用数据！')
              this.fullscreenLoading = false;
            }
          })
        }else{
          this.$message.error('至少选择一项打印！')
        }
      },
      refreshPrint(){
        this.printbottomData = ['emp_basic','emp_detail','family','emp_languageLevel','emp_workExp','education','emp_paper','emp_referee','emp_rewordPunishment','emp_furtherEdu']
        this.printTopData = []
      },
      selectPrint(){
        this.printbottomData = []
        this.printTopData = ['emp_basic','emp_detail','family','emp_languageLevel','emp_workExp','education','emp_paper','emp_referee','emp_rewordPunishment','emp_furtherEdu']
      },
      clearPrint(){
        this.refreshPrint()
        this.printModal = false
      },
      topClick(item,index){
        this.printTopData.splice(index,1)
        this.printbottomData.push(item)
      },
      bottomClick(item,index){
        this.printbottomData.splice(index,1)
        this.printTopData.push(item)
      },
      empDetail(row) {
        window.sessionStorage.setItem('pId',row.pid)
        // this.$router.push('/empDetail')
        const { href } = this.$router.resolve({path:'/empDetail'});
        window.open(href, '_blank');
      },
      empInsert() {
        window.sessionStorage.setItem('isPlayer',2)
        this.$router.push('/personInsert')
      },
      printEvent() {
        let topHtml = '<h2>教练员名单</h2>'
        this.searchEvent()
        setTimeout(()=>{
          this.$refs.empTable.print({
              sheetName: '教练员名单',
              beforePrintMethod: ({content}) => {
                  return topHtml + content
              }
          })
        },1000)
      },
      exportAllDataEvent() {
        this.loading = true
        setTimeout(() => {
          this.$refs.empTable.exportData({
            filename: '教职员名单',
            isHeader: true,
            isFooter: true,
            data: this.search?this.empData:this.defaultEmpData
          })
          this.loading = false
        }, 100)
      },
      clearTableFilter() {
        this.filterName = ''
        this.empPluralityTypeId = ''
        this.age = ''
        this.sportId = ''
        this.sportItemId = ''
        this.professionTypeId = ''
        this.empstatusId = ''
        this.selectDate = ''
        this.$refs.empTable.clearFilter()
        this.getEmp()
      },
      searchSubmit() {
        let data = {}
        if(this.empPluralityTypeId.length != 0) {
          data.empTypeIdStr = this.empPluralityTypeId.join(',')
        }
        if(this.age.length != 0) {
          data.ageStr = this.age.join(',')
        }
        if(this.sportId) {
          data.sportId = this.sportId
        }
        if(this.sportItemId) {
          data.sportItemId = this.sportItemId
        }
        if(this.empstatusId) {
          data.empStatusId = this.empstatusId
        }
        if(this.professionTypeId) {
          data.professionTypeId = this.professionTypeId
        }
        if(this.selectDate) {
          data.startDate = this.selectDate[0] + ' 00:00:00'
          data.endDate = this.selectDate[1] + ' 00:00:00'
        }
        getAllEmp(data).then(res=>{
          if(res.code === 200 && res.data.length!=0) {
            this.page = {
              currentPage: 1,
              pageSize: 10,
              totalResult: 0
            }
            this.init_data(res.data)
          }else{
            this.defaultEmpData = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      sportChange(option) {
        this.sportItemData = ''
        this.sportItemId = ''
        sport_item_by_sportId({sportId:option}).then(res=>{
          if(res.code === 200){
            this.sportItemData = res.data
          }
        })
      },
      selectAgeAll() {
        let arr = []
        for(let i = 1;i<= 100; i++){
          arr.push(i)
        }
        this.age = arr
      },
      customStringFilterMethod({ option, row, column}) {
        if (option.data) {
          return this.$XEUtils.toValueString(row[column.property]).toLowerCase().indexOf(option.data) > -1
        }
      },
      filterEvent(option) {
        const xTable = this.$refs.empTable
        // 设置为选中状态
        option.checked = true
        // 修改条件之后，需要手动调用 updateData 处理表格数据
        xTable.updateData()
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultEmpData.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterName) > -1))
          this.empData = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
            currentPage: 1,
            pageSize: this.empData.length,
            totalResult: this.empData.length
          }
          this.search = true
        } else {
          this.empData = this.defaultEmpData
        }
      },
      getEmp() {
        this.loading = true
        empInit().then(res=>{
          if(res.code === 200 && res.data.length!=0) {
            this.init_data(res.data)
          }else{
            this.defaultEmpData = []
          }
        }).then(()=>{
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        let dict_gender = {1:'男',2:'女'}
        data.forEach(item=>{
          item.idNo = this.dict_idNo[item.pid]
          item.genderName = dict_gender[item.genderId]
          item.empType = this.dict_emp_type[item.empTypeId]
          if(item.height){
            let heightArr = item.height.split(',')
            let heightStr = []
            heightArr.forEach(item=>{
              heightStr.push(this.dict_emp_type[item])
            })
            item.heightName = heightStr.join(',')
          }
          if(item.workDate){
            item.workDate = this.$moment(item.workDate).format('YYYY-MM-DD')
          }
          if(item.teachDate){
            item.teachDate = this.$moment(item.teachDate).format('YYYY-MM-DD')
          }
          if(item.leaveDate){
            item.leaveDate = this.$moment(item.leaveDate).format('YYYY-MM-DD')
          }
          item.professionType = this.dict_profession_type[item.professionTypeId]
          item.empStatus = this.dict_employee_status[item.empStatusId]
          item.sport = this.dict_sport[item.sportId]
          item.sportItem = this.dict_sport_item[item.sportItemId]
        })
        this.searchProps = Object.keys(data[0])
        this.defaultEmpData = data
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
            for(let i=15;i<=85;i++){
              this.ageArr.push(i)
            }
            employee_type().then(res=>{
              this.dict_emp_type = res
            })
            profession_type().then(res=>{
              this.dict_profession_type = res
            })
            employee_status().then(res=>{
              this.dict_employee_status = res
            })
            sport_by_org().then(res=>{
              this.dict_sport = res
            })
            sport_item().then(res=>{
              this.dict_sport_item = res
            })
            getPersonByOrgEmp().then(res=>{
              let dict_idNo = {}
              res.data.forEach(item=>{
                dict_idNo[item.pid] = item.idNo
              })
              this.dict_idNo = dict_idNo
              resolve()
            })
        })
      },
      handlePageChange({currentPage,pageSize}) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
        if(!this.search){
          this.page.pageSize = this.defaultEmpData.length
          this.findList()
        }else{
          this.page.pageSize = this.empData.length
        }
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.defaultEmpData.length
          this.empData = this.defaultEmpData.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
        }, 500)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .referEmp{
    .table{
      width: 100%;
      height: 100%;
      background-color: #fff;
      padding: 0 10px;

      .operate{
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;


        .vxe-button+.vxe-button, .vxe-button+.vxe-button--dropdown, .vxe-input+.vxe-button, .vxe-input+.vxe-button--dropdown{
          margin-left: 0;
        }
        .vxe-button{
          color: #0DA883;
          &:hover{
            color: #81cb94;
            text-decoration: underline;
          }
        }
      }
    }
    .print{
      width: 100%;
      height: 130px;
      border: 1px solid #0DA883;
      padding: 10px;
      display: flex;
      align-items: flex-start;
      flex-wrap: wrap;

      .el-button{
        margin: 0 5px;
      }
    }

    .print-top{
      margin-bottom: 10px;
    }
    .flex{
      display: flex;
    }
  }
</style>
